package com.artlongs.webapp.postman;

import com.artlongs.base.vo.BizRetVo;
import com.google.gson.Gson;
import reactor.event.Event;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Function:邮递员，干活吧
 *
 * @version $Revision$ $Date$
 *          Date: 15-12-23
 *          Time: 上午11:05
 * @author: monda
 * @since 3.0
 */
public interface Postman {
    final static String key = "252@#rgdf$%";

    public BizRetVo<Event> send(String toUrl, Event data);

    public BizRetVo<Event> receive(String data);

    /**
     * Event数据加密后转字串，以备传输
     * @param data
     * @return
     */
    default String zip(Event data) {
        Gson gson = new Gson();
        String dataJson = gson.toJson(data);
        try {
            dataJson = URLEncoder.encode(dataJson, "utf-8");
            dataJson = DesKeygenUtil.encrypt(key, dataJson);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return dataJson;
    }

    /**
     * 收到的字串解密后，转为Event
     * @param dataStr
     * @return
     */
    default Event unzip(String dataStr) {
        Gson gson = new Gson();
        try {
            dataStr = DesKeygenUtil.decrypt(key, dataStr);
            dataStr = URLDecoder.decode(dataStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Event data = gson.fromJson(dataStr,Event.class);

        return data;
    }

}
